package com.jt.service;

import com.jt.vo.ImageVO;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Service
public class FileServiceImpl implements FileService{

    private String rootDir="D:/images";   //磁盘根目录

    private String rootURl="http://image.jt.com"; //图片服务器网址
    /**
     * 1.校验文件是否为图片  校验图片类型
     * 2.防止文件为恶意程序  木马.exe.jpg
     * 3.分目录存储         按照时间维度划分
     * 4.防止文件重名       UUID
     * @param file
     * @return
     */
    @Override
    public ImageVO upload(MultipartFile file) {
        /**
         * rootDir:D:/images
         * fileName: xxxx.jpg
         * datePath:/2022/04/23/
         * fileDir: D:/images/2022/04/23/
         * fileType:  .jpg
         * path:D:/images/2022/04/23/xxxx.jpg
         * virtualPath:/2022/04/23/xxxx.jpg
         * rootURl:http://image.jt.com
         */
        //1.
        String fileName = file.getOriginalFilename().toLowerCase();
        if (!fileName.matches("^.+\\.(jpg|png|gif)$")){
            return null;
        }

        //2.通过宽高判断图片
        try {
            BufferedImage bufferedImage = ImageIO.read(file.getInputStream());
            int width = bufferedImage.getWidth();
            int height = bufferedImage.getHeight();
            if (width==0||height==0){
                return null;
            }
            //3.分目录存储
            String datePath=new SimpleDateFormat("/yyyy/MM/dd/").format(new Date());
            //实际磁盘目录
            String fileDir = rootDir+datePath;
            File dirFile=new File(fileDir);
            if (!dirFile.exists()){
                dirFile.mkdirs();
            }

            //4.
            String uuid= UUID.randomUUID().toString();
            int index=fileName.lastIndexOf(".");
            //.jpg
            String fileType=fileName.substring(index);
            //文件名
            fileName=uuid+fileType;

            //5.全路径  上传
            String path=fileDir+fileName;
            file.transferTo(new File(path));

            //6
            String virtualPath=datePath+fileName;
            String urlPath=rootURl+virtualPath;
            System.out.println(urlPath);
            ImageVO imageVO=new ImageVO(virtualPath,urlPath,fileName);
            return imageVO;
        }catch (IOException e){
            e.printStackTrace();
            throw new RuntimeException(e);
        }

    }

    /**
     * 文件删除
     * @param virtualPath
     */
    @Override
    public void deleteFile(String virtualPath) {
        String localPath=rootDir+virtualPath;
        File file=new File(localPath);
        if (file.exists()){
            file.delete();
        }
    }
}
